using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Asphodel.GameLogic;
using Asphodel.Client;


namespace Asphodel.Networking
{


	public class Client
	{
		private UdpClient udpSocket;
		private Int32 port;
		private Thread recvThread;
		private delegate void OnData(string message);
		private OnData dataDelegate;
		
		public Client()
		{
			this.port = 11650;
			
			this.udpSocket = new UdpClient(this.port);
			
			dataDelegate = new OnData(Logic.OnData);
			recvThread = new Thread(new ThreadStart(this.Receive));
			recvThread.IsBackground = true;
			recvThread.Start();
		}
		
		public void Send(Byte[] sendBytes, IPEndPoint ip)
		{
			udpSocket.Send(sendBytes, sendBytes.Length, ip);
		}
		
		public void Send(String message, IPEndPoint ip)
		{
			Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
			udpSocket.Send(sendBytes, sendBytes.Length, ip);
		}
		
		public void Send(Byte[] sendBytes, String host, int port)
		{
			
			IPEndPoint ip = new IPEndPoint(IPAddress.Parse(host), port);
			udpSocket.Send(sendBytes, sendBytes.Length, ip);
		}
		
		public void Send(String message, String host, int port)
		{
			IPEndPoint ip = new IPEndPoint(IPAddress.Parse(host), port);
			Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
			udpSocket.Send(sendBytes, sendBytes.Length, ip);
		}
		
		public void Receive()
		{
			while (true)
			{
				IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, this.port);
				byte[] content = udpSocket.Receive(ref remoteIP);
				
				if (content.Length > 0)
				{
					string message = Encoding.ASCII.GetString(content);
					dataDelegate(message);
				}
			}
		}
		
	}
}
